package com.example.star.view.activity;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.star.R;
import com.example.star.adapter.SongAdapter;
import com.example.star.api_service.SongApi;
import com.example.star.entity.Song;
import com.example.star.retrofit.ApiClient;

import java.io.IOException;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SongsActivity extends AppCompatActivity {
    public static final String EXTRA_SINGER_NAME = "extra_singer_name";

    private ListView listView;
    private SongAdapter songAdapter;
    private TextView noSongsText;
    private MediaPlayer mediaPlayer;
    private SeekBar seekBar;
    private TextView currentTimeTextView;
    private TextView totalTimeTextView;
    private Button playButton;
    private Button prevButton;
    private Button nextButton;
    private Handler handler = new Handler();
    private int currentSongIndex = 0; // 当前播放歌曲的索引

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_songs);

        listView = findViewById(R.id.listView);
        noSongsText = findViewById(R.id.no_songs_text);
        seekBar = findViewById(R.id.seek_bar);
        currentTimeTextView = findViewById(R.id.current_time_textview);
        totalTimeTextView = findViewById(R.id.total_time_textview);
        playButton = findViewById(R.id.play_button);
        prevButton = findViewById(R.id.prev_button);
        nextButton = findViewById(R.id.next_button);

        // 获取传递过来的歌手名
        String singerName = getIntent().getStringExtra(EXTRA_SINGER_NAME);
        if (singerName != null) {
            SongApi songApi = ApiClient.getClient().create(SongApi.class);
            Call<List<Song>> call = songApi.getSongsBySingerName(singerName);
            call.enqueue(new Callback<List<Song>>() {
                @Override
                public void onResponse(Call<List<Song>> call, Response<List<Song>> response) {
                    if (response.isSuccessful()) {
                        List<Song> songs = response.body();
                        if (songs != null && !songs.isEmpty()) {
                            songAdapter = new SongAdapter(SongsActivity.this, songs);
                            listView.setAdapter(songAdapter);
                            // 有歌曲时隐藏提示信息
                            noSongsText.setVisibility(View.GONE);

                            // 为列表项添加点击监听器，用于选择音乐播放
                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    currentSongIndex = position;
                                    Song selectedSong = songs.get(position);
                                    playMusic(selectedSong);
                                }
                            });

                            // 为按钮添加点击监听器
                            playButton.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (mediaPlayer != null) {
                                        if (mediaPlayer.isPlaying()) {
                                            mediaPlayer.pause();
                                            playButton.setText("播放");
                                        } else {
                                            mediaPlayer.start();
                                            playButton.setText("暂停");
                                        }
                                    } else {
                                        if (songs.size() > 0) {
                                            Song firstSong = songs.get(0);
                                            playMusic(firstSong);
                                        } else {
                                            Toast.makeText(SongsActivity.this, "没有可播放的歌曲", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }
                            });

                            prevButton.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (currentSongIndex > 0) {
                                        currentSongIndex--;
                                        Song prevSong = songs.get(currentSongIndex);
                                        playMusic(prevSong);
                                    } else {
                                        Toast.makeText(SongsActivity.this, "已经是第一首歌曲", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });

                            nextButton.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (currentSongIndex < songs.size() - 1) {
                                        currentSongIndex++;
                                        Song nextSong = songs.get(currentSongIndex);
                                        playMusic(nextSong);
                                    } else {
                                        Toast.makeText(SongsActivity.this, "已经是最后一首歌曲", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });

                            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                                @Override
                                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                    if (fromUser && mediaPlayer != null) {
                                        mediaPlayer.seekTo(progress);
                                    }
                                }

                                @Override
                                public void onStartTrackingTouch(SeekBar seekBar) {
                                }

                                @Override
                                public void onStopTrackingTouch(SeekBar seekBar) {
                                }
                            });
                        } else {
                            // 没有歌曲时显示提示信息
                            noSongsText.setVisibility(View.VISIBLE);
                        }
                    } else {
                        Toast.makeText(SongsActivity.this, "请求失败：" + response.code(), Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<List<Song>> call, Throwable t) {
                    Toast.makeText(SongsActivity.this, "网络请求失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            Toast.makeText(this, "未获取到歌手名", Toast.LENGTH_SHORT).show();
        }
    }

    private void playMusic(Song song) {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(song.getMusicData()); // 假设 Song 类有 getMusicData 方法获取音乐文件路径
            mediaPlayer.prepare();
            mediaPlayer.start();
            playButton.setText("暂停");
            seekBar.setMax(mediaPlayer.getDuration());
            updateSeekBar();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    // 播放完一首歌曲后自动播放下一首
                    currentSongIndex++;
                    if (currentSongIndex < songAdapter.getCount()) {
                        Song nextSong = songAdapter.getItem(currentSongIndex);
                        playMusic(nextSong);
                    } else {
                        // 播放完最后一首歌曲，停止播放
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaPlayer = null;
                        playButton.setText("播放");
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(SongsActivity.this, "播放失败，文件格式可能不支持", Toast.LENGTH_SHORT).show();
            if (mediaPlayer != null) {
                mediaPlayer.release();
                mediaPlayer = null;
            }
        }
    }

    private void updateSeekBar() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mediaPlayer != null) {
                    int currentPosition = mediaPlayer.getCurrentPosition();
                    seekBar.setProgress(currentPosition);
                    currentTimeTextView.setText(formatTime(currentPosition));
                    totalTimeTextView.setText(formatTime(mediaPlayer.getDuration()));
                    handler.postDelayed(this, 1000);
                }
            }
        }, 1000);
    }

    private String formatTime(int time) {
        int totalSeconds = time / 1000;
        int minutes = totalSeconds / 60;
        int seconds = totalSeconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        handler.removeCallbacksAndMessages(null);
    }
}